<template>
  <div class="orders-page">
    <!-- 顶部导航栏 -->
    <Header />
    
    <div class="main-content">
      <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('nav.orders') }}</h1>
          <p>查看和管理您的所有订单</p>
        </div>
        
        <!-- 订单筛选 -->
        <div class="filter-section">
          <a-tabs v-model:activeKey="activeStatus" @change="handleStatusChange">
            <a-tab-pane key="all" tab="全部订单" />
            <a-tab-pane key="pending" tab="待付款" />
            <a-tab-pane key="paid" tab="已付款" />
            <a-tab-pane key="shipped" tab="已发货" />
            <a-tab-pane key="delivered" tab="已送达" />
            <a-tab-pane key="completed" tab="已完成" />
            <a-tab-pane key="cancelled" tab="已取消" />
          </a-tabs>
        </div>
        
        <!-- 订单列表 -->
        <div class="orders-list">
          <div v-if="loading" class="loading-container">
            <a-spin size="large" />
            <p>正在加载订单...</p>
          </div>
          
          <div v-else-if="filteredOrders.length === 0" class="empty-state">
            <InboxOutlined class="empty-icon" />
            <h3>暂无订单</h3>
            <p>您还没有任何订单，快去购物吧！</p>
            <a-button type="primary" @click="goToProducts">
              去购物
            </a-button>
          </div>
          
          <div v-else class="orders-container">
            <div v-for="order in filteredOrders" :key="order.id" class="order-card">
              <!-- 订单头部 -->
              <div class="order-header">
                <div class="order-info">
                  <span class="order-id">订单号：{{ order.id }}</span>
                  <span class="order-date">{{ formatDate(order.createTime) }}</span>
                </div>
                <div class="order-status">
                  <span class="status-tag" :class="order.status">
                    {{ getOrderStatusText(order.status) }}
                  </span>
                </div>
              </div>
              
              <!-- 订单商品 -->
              <div class="order-products">
                <div v-for="product in order.products" :key="product.id" class="product-item">
                  <div class="product-image">
                    <img :src="product.images ? product.images[0] : product.image" :alt="product.name" />
                  </div>
                  <div class="product-info">
                    <h4 class="product-name">{{ product.name }}</h4>
                    <p class="product-spec">{{ product.specification }}</p>
                    <div class="product-price">
                      <span class="price">¥{{ product.price }}</span>
                      <span class="quantity">×{{ product.quantity }}</span>
                    </div>
                  </div>
                  <div class="product-actions">
                    <a-button 
                      size="small" 
                      @click="viewProductDetail(product.id)"
                    >
                      查看商品
                    </a-button>
                    <a-button 
                      v-if="order.status === 'completed'"
                      size="small" 
                      @click="writeReview(product.id)"
                    >
                      评价
                    </a-button>
                  </div>
                </div>
              </div>
              
              <!-- 订单统计 -->
              <div class="order-summary">
                <div class="summary-info">
                  <span>共 {{ getTotalQuantity(order.products) }} 件商品</span>
                  <span class="total-price">总计：¥{{ order.totalAmount }}</span>
                </div>
              </div>
              
              <!-- 订单操作 -->
              <div class="order-actions">
                <a-button size="small" @click="viewOrderDetail(order.id)">
                  查看详情
                </a-button>
                
                <a-button 
                  v-if="order.status === 'pending'"
                  size="small" 
                  type="primary"
                  @click="payOrder(order.id)"
                >
                  立即付款
                </a-button>
                
                <a-button 
                  v-if="order.status === 'pending'"
                  size="small" 
                  danger
                  @click="cancelOrder(order.id)"
                >
                  取消订单
                </a-button>
                
                <a-button 
                  v-if="order.status === 'delivered'"
                  size="small" 
                  type="primary"
                  @click="confirmReceived(order.id)"
                >
                  确认收货
                </a-button>
                
                <a-button 
                  v-if="order.status === 'completed'"
                  size="small"
                  @click="buyAgain(order)"
                >
                  再次购买
                </a-button>
                
                <a-button 
                  v-if="order.status === 'completed'"
                  size="small"
                  @click="applyRefund(order.id)"
                >
                  申请退款
                </a-button>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="filteredOrders.length > 0" class="pagination-container">
            <a-pagination
              v-model:current="currentPage"
              v-model:pageSize="pageSize"
              :total="totalOrders"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
              @change="handlePageChange"
              @showSizeChange="handlePageSizeChange"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部信息 -->
    <Footer />
    
    <!-- 取消订单确认弹窗 -->
    <a-modal
      v-model:open="showCancelModal"
      title="取消订单"
      @ok="confirmCancelOrder"
    >
      <p>确定要取消这个订单吗？取消后无法恢复。</p>
    </a-modal>
    
    <!-- 确认收货弹窗 -->
    <a-modal
      v-model:open="showConfirmModal"
      title="确认收货"
      @ok="confirmReceivedOrder"
    >
      <p>确认已收到商品吗？确认后将无法申请退款。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'

// 使用Vuex store和Vue Router
const store = useStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const showCancelModal = ref(false)
const showConfirmModal = ref(false)
const cancelOrderId = ref(null)
const confirmOrderId = ref(null)

// 模拟订单数据 - 将通过API获取
const orders = ref([])

// 计算属性
const filteredOrders = computed(() => {
  if (activeStatus.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => order.status === activeStatus.value)
})

const totalOrders = computed(() => filteredOrders.value.length)

// 方法
const handleStatusChange = (key) => {
  activeStatus.value = key
  currentPage.value = 1
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const handlePageSizeChange = (current, size) => {
  currentPage.value = 1
  pageSize.value = size
}

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    delivered: '已送达',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getTotalQuantity = (products) => {
  return products.reduce((total, product) => total + product.quantity, 0)
}

const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

const viewProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const payOrder = (orderId) => {
  router.push(`/checkout?orderId=${orderId}`)
}

const cancelOrder = (orderId) => {
  cancelOrderId.value = orderId
  showCancelModal.value = true
}

const confirmCancelOrder = () => {
  const orderIndex = orders.value.findIndex(order => order.id === cancelOrderId.value)
  if (orderIndex !== -1) {
    orders.value[orderIndex].status = 'cancelled'
    message.success('订单已取消')
  }
  showCancelModal.value = false
  cancelOrderId.value = null
}

const confirmReceived = (orderId) => {
  confirmOrderId.value = orderId
  showConfirmModal.value = true
}

const confirmReceivedOrder = () => {
  const orderIndex = orders.value.findIndex(order => order.id === confirmOrderId.value)
  if (orderIndex !== -1) {
    orders.value[orderIndex].status = 'completed'
    message.success('已确认收货')
  }
  showConfirmModal.value = false
  confirmOrderId.value = null
}

const buyAgain = (order) => {
  // 将订单中的商品添加到购物车
  order.products.forEach(product => {
    store.dispatch('cart/addToCart', {
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.image,
      quantity: product.quantity
    })
  })
  
  message.success('已添加到购物车')
  router.push('/cart')
}

const applyRefund = (orderId) => {
  message.info('退款申请功能开发中')
}

const writeReview = (productId) => {
  message.info('评价功能开发中')
}

const goToProducts = () => {
  router.push('/products')
}

// 生命周期
onMounted(() => {
  // 这里可以加载用户的订单数据
  loading.value = true
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.value = false
  }, 1000)
})
</script>

<style scoped>
.orders-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.filter-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.orders-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-container p {
  margin-top: 15px;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: #d9d9d9;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
}

.empty-state p {
  color: #666;
  margin: 0 0 20px 0;
}

.orders-container {
  padding: 20px;
}

.order-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-card:last-child {
  margin-bottom: 0;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-id {
  font-weight: 500;
  color: #333;
}

.order-date {
  font-size: 12px;
  color: #666;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-tag.paid {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag.shipped {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.delivered {
  background: #f0f5ff;
  color: #722ed1;
}

.status-tag.completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.cancelled {
  background: #fff2f0;
  color: #ff4d4f;
}

.order-products {
  padding: 20px;
}

.product-item {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.product-image img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.product-spec {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #666;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price {
  font-weight: 600;
  color: #333;
}

.quantity {
  color: #666;
  font-size: 12px;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  justify-content: center;
}

.order-summary {
  padding: 15px 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}

.summary-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.total-price {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 10px;
  padding: 15px 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px 0;
  }
  
  .page-header {
    padding: 20px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .orders-container {
    padding: 15px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-item {
    flex-direction: column;
    gap: 10px;
  }
  
  .product-actions {
    flex-direction: row;
    justify-content: flex-start;
  }
  
  .order-actions {
    flex-direction: column;
  }
  
  .order-actions .ant-btn {
    width: 100%;
  }
  
  .summary-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style> 